/*
 *所有关于cailiao_plan_data类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*cailiao_plan_dataService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.DbSqlSugar;
using DGZImp.Core.EFDbContext;
using NetTaste;
using static ATkg.BizAppProject.Services.table_wgjyService;
using Newtonsoft.Json.Linq;
using DGZImp.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Components.Forms;


namespace ATkg.BizAppProject.Services
{
    public partial class cailiao_plan_dataService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Icailiao_plan_dataRepository _repository;//访问数据库
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public AmesSyncService ames = AutofacContainerModule.GetService<AmesSyncService>();

        [ActivatorUtilitiesConstructor]
        public cailiao_plan_dataService(
            Icailiao_plan_dataRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public class SteelName1
        {
            public string steelgrade_id;
            public int batch_todo_qty;
            public int total_weight;


        }
        public async Task<object> get_db_data_cailiao_plan()
        {
            Console.WriteLine("进来了！！");
            var data = await Db.Set<cailiao_plan_data>()
                .Select(x => new
                {
                    x.SteelgradeName,  // 替换为你的字段名
                    x.TotalWeightPer,
                    x.Material1,
                    x.Material2,
                    x.Material3,
                    x.Material4,
                    x.Material5
                })
                .ToListAsync();
            Console.WriteLine(data);
            return data;
        }
        public class Record
        {
            public int id { get; set; }
            public int product_qty { get; set; }
            public int product_done_stock_accum_qty { get; set; }
            // 其他字段...
        }
        public class ResultContainer
        {
            public int length { get; set; }
            public List<Record> records { get; set; }
        }
        public async Task<object> get_info_from_bfmes()
        {
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";
            //var isSingle = taskNo.IsValuable();
            //Console.WriteLine(taskNo);
            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {

                new List<object> { "production_type", "=", "final" }
            };

            var qFields = new List<string> {
                "id",
                "raw_lot_id",
                "product_id",
                "prodcut_spec",
                "grade",
                "raw_resume_stock_qty",
                "partner_id"
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            // 1. 构建domain条件树
            var domain1 = new List<object>
            {
                "&", "&",
                new List<object> { "workshop_type", "=", "material" },
                new List<object> { "state", "!=", "draft" },
                "&",
                new List<object> { "supply_strategy","=", "outsourcing" },
                "&",
                new List<object> { "schedule_state", "not in", new List<object> { "draft", "cancel", "pause" } },
                new List<object> { "state", "in", new List<object> { "ready", "confirmed", "in_production" } }
            };

            // 2. 构建specification字段映射
            var specification = new Dictionary<string, object>
            {
                {
                    "schedule_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "top_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "grade", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "schedule_blank_spec", new Dictionary<string, object>() },
                {
                    "mold_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "steelgrade_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "date_first_batch", new Dictionary<string, object>() },
                { "date_finished", new Dictionary<string, object>() },
                { "product_qty", new Dictionary<string, object>() },
                { "product_done_stock_accum_qty", new Dictionary<string, object>() }
            };

            // 3. 组合最终结构
            var result = new Dictionary<string, object>
            {
                { "domain", domain1 },
                { "specification", specification }
            };

            var resp = await ames.Get_web_search_read("mps.schedule.line", result);
            Console.WriteLine(resp);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"]["records"];
            Console.WriteLine(record);
            Console.WriteLine(record[0]["schedule_id"]["display_name"]);


            var final_data_info = new List<object>();

            for(int i = 0; i < record.Count; i++)
            {
                var final_data = new Dictionary<string, object> { };
                Console.WriteLine(record[i]["schedule_id"]["display_name"]);
                int id_sche = (int)record[i]["schedule_id"]["id"];
                var resp_wt = await ames.Get_web_read("mps.schedule", id_sche);
                Console.WriteLine("11111111111111111");
                Console.WriteLine(resp_wt);
                Console.WriteLine("11111111111111111");
                decimal per_weight_ = (decimal)resp_wt["result"][0]["weight"];
                decimal per_weight = Math.Round(per_weight_, 4);


                //查询冶炼
                // 1. 构建domain条件树（查询筛选条件） 
                var domain_yl = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "alloy" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel" }, // 包含列表值的条件
                };

                        // 2. 构建specification字段映射规范
                var specification_yl = new Dictionary<string, object>
                {
                    { "produced_qty", new Dictionary<string, object>() }, // 空配置字段
                    { "product_qty", new Dictionary<string, object>() }          // 空配置字段
                };

                        // 3. 组合最终结构
                var result_yl = new Dictionary<string, object>
                {
                    { "domain", domain_yl },
                    { "specification", specification_yl }
                };
                var resp_yl = await ames.Get_web_search_read("mrp.production", result_yl);
                Console.WriteLine("11111111111111111");
                //Console.WriteLine(resp_yl);

                var record_yl = (JArray)resp_yl["result"]["records"];
                decimal InputQty_yl = 0.0m;
                decimal Qty_yl = 0.0m;
                for(int y = 0; y < record_yl.Count; y++)
                {
                    InputQty_yl += (decimal)record_yl[y]["produced_qty"];
                    Qty_yl += (decimal)record_yl[y]["product_qty"];
                }


                Console.WriteLine("11111111111111111");
                // 查询氢破粉
                // 1. 构建domain条件树（查询筛选条件）
                var domain_qp = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "powder" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "product_id.atm_type","=", "powder1" },
                    "&",
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel" }, // 包含列表值的条件
                };

                // 2. 构建specification字段映射规范
                var specification_qp = new Dictionary<string, object>
                {
                    { "produced_qty", new Dictionary<string, object>() }, // 空配置字段
                    { "product_qty", new Dictionary<string, object>() }          // 空配置字段
                };

                // 3. 组合最终结构
                var result_qp = new Dictionary<string, object>
                {
                    { "domain", domain_qp },
                    { "specification", specification_qp }
                };
                var resp_qp = await ames.Get_web_search_read("mrp.production", result_qp);
                Console.WriteLine("22222222222222222");
                //Console.WriteLine(resp_qp);
                var record_qp = (JArray)resp_qp["result"]["records"];
                decimal InputQty_qp = 0.0m;
                decimal Qty_qp = 0.0m;
                for (int y = 0; y < record_qp.Count; y++)
                {
                    InputQty_qp += (decimal)record_qp[y]["produced_qty"];
                    Qty_qp += (decimal)record_qp[y]["product_qty"];
                }
                Console.WriteLine("22222222222222222");


                // 查询气流磨
                // 1. 构建domain条件树（查询筛选条件）
                var domain_qlm = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "powder" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "product_id.atm_type","=", "powder2" },
                    "&",
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel"}, // 包含列表值的条件
                };
                // 3. 组合最终结构
                var result_qlm = new Dictionary<string, object>
                {
                    { "domain", domain_qlm },
                    { "specification", specification_qp }
                };
                var resp_qlm = await ames.Get_web_search_read("mrp.production", result_qlm);
                Console.WriteLine("33333333333333333");
                //Console.WriteLine(resp_qlm);
                var record_qlm = (JArray)resp_qlm["result"]["records"];
                decimal InputQty_qlm = 0.0m;
                decimal Qty_qlm = 0.0m;
                for (int y = 0; y < record_qlm.Count; y++)
                {
                    InputQty_qlm += (decimal)record_qlm[y]["produced_qty"];
                    Qty_qlm += (decimal)record_qlm[y]["product_qty"];
                }
                Console.WriteLine("33333333333333333");



                

                // 查询压型
                // 1. 构建domain条件树（查询筛选条件）
                var domain_yx = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "blank" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "product_id.atm_type","=", "press" },
                    "&",
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel"}, // 包含列表值的条件
                };
                // 3. 组合最终结构
                var result_yx = new Dictionary<string, object>
                {
                    { "domain", domain_yx },
                    { "specification", specification_qp }
                };
                var resp_yx = await ames.Get_web_search_read("mrp.production", result_yx);
                Console.WriteLine("55555555555555555");
                //Console.WriteLine(resp_qlm);
                var record_yx = (JArray)resp_yx["result"]["records"];
                decimal InputQty_yx = 0.0m;
                decimal Qty_yx = 0.0m;
                for (int y = 0; y < record_yx.Count; y++)
                {
                    InputQty_yx += (decimal)record_yx[y]["produced_qty"];
                    Qty_yx += (decimal)record_yx[y]["product_qty"];
                }
                Console.WriteLine("55555555555555555");


                // 查询烧结
                // 1. 构建domain条件树（查询筛选条件）
                var domain_sj = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "blank" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "product_id.atm_type","=", "press" },
                    "&",
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel"}, // 包含列表值的条件
                };
                // 3. 组合最终结构
                var result_sj = new Dictionary<string, object>
                {
                    { "domain", domain_sj },
                    { "specification", specification_qp }
                };
                var resp_sj = await ames.Get_web_search_read("mrp.production", result_sj);
                Console.WriteLine("66666666666666666");
                //Console.WriteLine(resp_qlm);
                var record_sj = (JArray)resp_sj["result"]["records"];
                decimal InputQty_sj = 0.0m;
                decimal Qty_sj = 0.0m;
                for (int y = 0; y < record_sj.Count; y++)
                {
                    InputQty_sj += (decimal)record_sj[y]["produced_qty"];
                    Qty_sj += (decimal)record_sj[y]["product_qty"];
                }
                Console.WriteLine("66666666666666666");




                string mold_id_name = "";
                try
                {
                    mold_id_name = (string)record[i]["mold_id"]["display_name"];
                }
                catch
                {
                    mold_id_name = "";
                }

                final_data = new Dictionary<string, object>
                {
                    { "schedule_id", record[i]["schedule_id"]["display_name"] }, // 空配置字段
                    { "top_id", record[i]["top_id"]["display_name"] },          // 空配置字段, // 空配置字段
                    { "grade", record[i]["grade"]["display_name"] },          // 空配置字段, // 空配置字段
                    { "schedule_blank_spec", record[i]["schedule_blank_spec"] },          // 空配置字段, // 空配置字段
                    { "mold_id", mold_id_name},          // 空配置字段, // 空配置字段
                    { "steelgrade_id", record[i]["steelgrade_id"]["display_name"] },          // 空配置字段, // 空配置字段
                    { "date_first_batch", record[i]["date_first_batch"] },          // 空配置字段, // 空配置字段
                    { "date_finished", record[i]["date_finished"] },          // 空配置字段, // 空配置字段
                    { "product_qty", record[i]["product_qty"] },          // 空配置字段          // 空配置字段, // 空配置字段
                    { "per_weight", per_weight },          // 空配置字段
                    { "total_weight",(decimal)per_weight * (decimal)record[i]["product_qty"] /1000 },
                    { "Qty_yl",Qty_yl },
                    { "InputQty_yl",InputQty_yl },
                    { "Qty_qp",Qty_qp },
                    { "InputQty_qp",InputQty_qp },
                    { "Qty_qlm",Qty_qlm },
                    { "InputQty_qlm",InputQty_qlm },
                    { "Qty_yx",Qty_yx },
                    { "InputQty_yx",InputQty_yx },
                    { "Qty_sj",Qty_sj },
                    { "InputQty_sj",InputQty_sj },
                };
                final_data_info.Add(final_data);

            }



            return final_data_info;
        }


        public async Task<string> up_to_mes_maopisongyang(string luhao,string time)
        {

            Console.WriteLine("毛坯送检！");
            ames.userName = "fangjifeng@atmcn.com";
            ames.password = "Fjf123456";
            ames.url = "http://10.7.1.3/jsonrpc";
            ames.db = "atm";

            //ames.userName = "duyang@atmcn.com";
            //ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";

            var qDomain = new List<object> {
                    new List<object> { "lot_id", "ilike", luhao},
                };
            Console.WriteLine(qDomain);
            var qFields = new List<string> {
                    "id"
                };
            var qPage_per = new
            { };
            var resp = await ames.Get_info_gzd("quality.point", qDomain, qFields, qPage_per);
            Console.WriteLine(resp);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            string up_state = "";
            if (res.Count > 0)
            {
                Console.WriteLine(res[0]["id"].ToString());
                int id_ = (int)res[0]["id"];
                var inputData = new Dictionary<string, object>
                        {
                            { "sample_recv_time", time }
                        };
                var resp_name_w = await ames.up_to_messys("quality.point", id_, inputData);
                Console.WriteLine(resp_name_w);
                if (resp.ContainsKey("error"))
                {
                    var message = $"【拉取单据】{resp["error"].ToString()}";
                    up_state = "上传错误";
                    throw new AppException(message);
                }
                else
                {
                    up_state = resp_name_w["result"].ToString();
                }
            }
            else
            {
                up_state = "未报工";
            }
            return up_state;
        }



    }
}
